﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FreeTextBoxControls;
using System.IO;
using System.Security.Principal;

public partial class Adm_Editor : System.Web.UI.Page
{
		protected string mDirectoryContenuti = string.Empty;
		protected string mBaseUrl = "~/public/";
		protected string mHostWeb = string.Empty;
		protected string mNomePagina = string.Empty;

		protected void Page_Load(object sender, EventArgs e)
		{
				mDirectoryContenuti = Server.MapPath(mBaseUrl);
				mHostWeb = Page.ResolveClientUrl(mBaseUrl);
				
				this.GridViewPagine.DataKeyNames = new []{"Pagina"}; 
				
				if (!Page.IsPostBack)
						initForm();

				bindaDati();

		}//fM

		protected void initForm()
		{


				Save tbbSave = new Save();
				Toolbar tb = new Toolbar();
				tb.Items.Add(tbbSave);
				txtFreeTB.Toolbars.Add(tb);
				txtFreeTB.Width = Unit.Percentage(100);
				//txtFreeTB.Height = Unit.Percentage(100);

		}

		private void bindaDati()
		{
				//GridViewPagine.DataKeyNames = new[]{"" }; 
				GridViewPagine.DataSource = getPagine();
				GridViewPagine.DataBind();

				myGridViewImmagini.DataSource = getImmaginicaricate();
				myGridViewImmagini.DataBind();
		}

		private IEnumerable<string> getImmaginicaricate()
		{
				DirectoryInfo dir = new DirectoryInfo(mDirectoryContenuti + "Img");
				FileSystemInfo[] arrFiles = dir.GetFileSystemInfos();
				var immagini = arrFiles.Select(d => d.Name);
				return immagini;
		}//fM

		private void Impersonate()
		{

				//var wId = HttpContext.Current.User.Identity as System.Web.Security.FormsIdentity ;
				////WindowsIdentity wIdb4 = WindowsIdentity.GetCurrent();
				////string name = wIdb4.Name;
				//Response.Write("Before impersonation" + name + "<br>");// <-- Writes ASPNET Account

				////Till this line,code is executed in the context of worker process
				//WindowsImpersonationContext wIdCon = wIdb4.Impersonate(); 
				//WindowsIdentity wIdafter = WindowsIdentity.GetCurrent();
				//name = wIdafter.Name;
				//Response.Write("After Impersonation " + name + "<br>");// <-- writes Logged in user

				////Run in the context of logged authenticated user, do your //operations that require impersonation
				//wIdCon.Undo();
				//WindowsIdentity wIdafterUndo = WindowsIdentity.GetCurrent();
				//name = wIdafterUndo.Name;
				//Response.Write("After undo Impersonation " + name + "<br>");
		}//fM
		
		
		private object getPagine()
		{
				//using (OrBudgetDataContext DAL = new OrBudgetDataContext())
				//{
				//  var q = DAL.HELP.Select(d => d.HEFORM).OrderBy(d => d);
				//  return q.ToList();
				//} 
				//////file system
				//List<string> lista=new List<string>() ;
				//string dire = ResolveUrl("~");

				DirectoryInfo dir = new DirectoryInfo(mDirectoryContenuti);
				FileSystemInfo[] arrFiles = dir.GetFileSystemInfos("*.aspx");
				var pagine = arrFiles.Select(d => new {Pagina= d.Name});
				return pagine;

		}//fM


		private string getPageHtml(string pPage)
		{
				//using (OrBudgetDataContext DAL = new OrBudgetDataContext())
				//{
				//  var q = DAL.HELP.Where(d => d.HEFORM.Equals(pPage))
				//      .Select(d => d.HEHELP);
				//  return q.SingleOrDefault();
				//}
				using (var stream = File.OpenText(mDirectoryContenuti + pPage))
				{
						if (stream == null)
						{ LiteralMsg.Text = "Errore : Non trovata !!"; stream.Close(); return string.Empty; }

						var contenuto = stream.ReadToEnd();
						stream.Close();
						contenuto = contenuto.Replace("<asp:Content ", "<##asp:Content ");
						contenuto = contenuto.Replace("</asp:Content>", "");
						return contenuto; //Server.HtmlEncode (contenuto);
				}
		}//fM

		//*************************EVENTI************************
		//*******************************************************

		protected void txtFreeTB_SaveClick(object sender, EventArgs e)
		{
				Security sec = new Security();
				string contenuto = this.txtFreeTB.Text;

				contenuto = Server.HtmlDecode(contenuto);
				contenuto = contenuto.Replace("<br>", "<br />");

				contenuto = contenuto.Replace("<##asp:Content ", "<asp:Content ");

				contenuto += "</asp:Content>";


				if (string.IsNullOrEmpty(contenuto)) return;

				if (string.IsNullOrEmpty(HiddenFieldPagina.Value))
				{
						this.LiteralMsg.Text = "Selezionare una pagina...";
						return;
				}

				try
				{
						bool appendi = false;
						mNomePagina = HiddenFieldPagina.Value;

						if (HiddenFieldPagina.Value == "[@newPage]")
						{
								appendi = false; mNomePagina = myTxtNomePagina.Text;
								HiddenFieldPagina.Value = myTxtNomePagina.Text;
								myTxtNomePagina.Text =string.Empty;
						}

						if (string.IsNullOrEmpty(mNomePagina))
						{
								LiteralMsg.Text = "Manca il nome della nuova pagina..."; return;
						}
						if (!mNomePagina.EndsWith(".aspx")) mNomePagina += ".aspx";

						string car;
						if (sec.CiSonoCarNonAmmessi(mNomePagina, out car))
						{ LiteralMsg.Text = "Errore : caratteri non ammessi nel nome pagina"; return; }

						using (var stream = new StreamWriter(mDirectoryContenuti + mNomePagina, appendi, System.Text.Encoding.Unicode, 512))
						{
								stream.Write(contenuto);
								stream.Flush();
								stream.Close();
						}

						myTextBoxTestoDebug.Text = contenuto;
						LiteralMsg.Text = "Pagina : " + mNomePagina + ", corretamente salvata " + DateTime.Now.ToLongTimeString();
						
						bindaDati();
				}
				catch (Exception ex)
				{
						LabelPagina.Text = "Errore Dati NON salvati : " + ex.Message;

				}


				//using (OrBudgetDataContext DAL = new OrBudgetDataContext())
				//{
				//  string txtHelp = this.txtFreeTB.Text;
				//  if (string.IsNullOrEmpty(HiddenFieldPagina.Value))
				//  {
				//    LabelPagina.Text = "Selezionare una pagina...";
				//    return;
				//  }
				//  if (string.IsNullOrEmpty(txtHelp)) txtHelp = " ";
				//  try
				//  {

				//    var dato = DAL.HELP.Where(d => d.HEFORM.Equals(HiddenFieldPagina.Value)).FirstOrDefault();
				//    if (dato != null)
				//    {
				//      dato.HEHELP = txtHelp;
				//      //dato.HEDESCRIZIONE = 
				//      dato.HEUPDATEDATE = DateTime.Now;
				//      dato.HEUPDATEUSER = User.Identity.Name;
				//    }
				//    else
				//    {
				//      HELP help = new HELP();
				//      help.HEFORM = LabelPagina.Text;
				//      help.HEHELP = txtHelp;
				//      help.HEUPDATEDATE = DateTime.Now;
				//      help.HEUPDATEUSER = User.Identity.Name;
				//      DAL.HELP.InsertOnSubmit(help);
				//    }
				//    DAL.SubmitChanges();

				//    LabelPagina.Text = "Dati salvati correttamente [" + DateTime.Now.ToLocalTime().ToString() + "]";

				//  }
				//  catch (Exception ex)
				//  {
				//    LabelPagina.Text = "Dati NON salvati \n" + ex.Message;

				//  }

				//}

		}//fM

		protected void GridViewPagine_SelectedIndexChanged(Object sender, EventArgs e)
		{
				GridViewRow row = ((GridView)sender).SelectedRow as GridViewRow;
				//var pathPage = ((GridView)sender).SelectedDataKey.Value.ToString() ;
				txtFreeTB.Text= string.Empty;
				
				if (row.Controls.Count < 2) return;
				DataControlFieldCell cell = row.Controls[2] as DataControlFieldCell;
				string pagina = cell.Text;
				if (string.IsNullOrEmpty(pagina)) return;
				
				actionPage(pagina, "showContenuti");
				 
		}//fM   



		protected void myButtonNuova_Click(object sender, EventArgs e)
		{
				LabelPagina.Text = "Pagina : [ nuova ]";
				HiddenFieldPagina.Value = "[@newPage]";
				txtFreeTB.Text = getTemplate(true);
		}

		private string getTemplate(bool contenuti)
		{
				return "<%@ Page Title=\"\" Language=\"C#\" MasterPageFile=\"~/Site.master\" %>\n" +
					"<##asp:Content ID=\"Content1\" ContentPlaceHolderID=\"ContentPlaceHolder1\" Runat=\"Server\">";


		}
		protected void myButtonVediPagina_Click(object sender, EventArgs e)
		{
				string nomePagina = HiddenFieldPagina.Value;

				if (HiddenFieldPagina.Value == "[@newPage]") nomePagina = myTxtNomePagina.Text;
				if (string.IsNullOrEmpty(nomePagina))
				{ LiteralMsg.Text = "Manca il nome della nuova pagina..."; return; }

				if (!nomePagina.EndsWith(".aspx")) nomePagina += ".aspx";

				Response.Redirect(mBaseUrl + nomePagina);
		}
		
		protected void myButtonSalvaImgUpload_Click(object sender, EventArgs e)
		{

				string filePath = Request.PhysicalApplicationPath;
				Response.Write(filePath);
				Response.Write("</br>" + mDirectoryContenuti);
				filePath = filePath += "public/Img/";

				string[] msg = new string[6];
				msg[0] = caricaFile(FileUpload1, filePath);
				msg[1] = caricaFile(FileUpload2, filePath);
				msg[2] = caricaFile(FileUpload3, filePath);
				msg[3] = caricaFile(FileUpload4, filePath);
				msg[4] = caricaFile(FileUpload5, filePath);
				msg[5] = caricaFile(FileUpload6, filePath);

				foreach (var item in msg)
				{
						if (item != string.Empty)
								this.myLiteralMsgUpload.Text += item + "</br>";
				}

		}//fM

		private string caricaFile(FileUpload fUp, string filePath)
		{
				try
				{
						if (fUp.HasFile)
						{
								filePath += fUp.FileName;
								fUp.SaveAs(filePath);
								return string.Empty;
						}
				}
				catch (Exception ex)
				{
						return ex.Message;
				}
				return string.Empty;

		}//fM

		protected void GridViewPagine_RowCommand(object sender, GridViewCommandEventArgs e)
		{

		}//fM

		private void actionPage( string pagina,string comando)
		{		   
				if (string.IsNullOrEmpty(pagina) )return ;
															
						string path = mDirectoryContenuti + pagina ;
      Response.Write(comando); 
						try
						{
								if (comando.Equals("cancella", StringComparison.InvariantCultureIgnoreCase ))//cancella la pagina
								{
								  Response.Write("cancella"); 
										//sposta su cancellate...
										File.Copy(path,mDirectoryContenuti+ "Cancellate/"+ pagina,true);
										
										File.Delete(path);
										LiteralMsg.Text = "Pagina " + pagina + " cancellata !! ";
										txtFreeTB.Text = string.Empty;
								}

								if (comando.Equals("showContenuti"))//contenuti della pagina
								{
										txtFreeTB.Text = getPageHtml(pagina);
										LabelPagina.Text = "Pagina : " + pagina;
										HiddenFieldPagina.Value = pagina;
										mNomePagina = pagina;
								}
								
								bindaDati();
						}
						catch (Exception ex)
						{
								LiteralMsg.Text = "Errore : "+ex.Message;
						}
						
		}//fM
		
		
		/////
		protected void GridViewPagine_RowDeleting(object sender, GridViewDeleteEventArgs e)
		{
				GridViewRow row = ((GridView)sender).Rows[e.RowIndex] as GridViewRow;
    if(row==null)return ;
				DataControlFieldCell cell = row.Controls[2] as DataControlFieldCell;
				var pagina = cell.Text;
				actionPage(pagina, "cancella" );				
				
		}
}//fC
